import log from 'fancy-log';
import chalk from 'chalk';

function compatibleSVGVariables(svgStr: string): string {
    const variableRegex = /"&(\w+);"|'&(\w+);'/gi;

    return svgStr?.replace(variableRegex, ($0, $1, $2) => {
        const matchGroup = $1 ?? $2;

        const valueRegex = new RegExp(`<!ENTITY ${matchGroup} "(.+)">`, 'i');

        const valueGroups = valueRegex.exec(svgStr);

        const isHasAnyMatchVariableValue = valueRegex.test(svgStr);
        isHasAnyMatchVariableValue && log(chalk.green(`replace variable: ${matchGroup} to ${valueGroups[1]}`));

        return isHasAnyMatchVariableValue ? $0.replace(`&${matchGroup};`, valueGroups[1]) : $0;
    });
}

export { compatibleSVGVariables };
